const { src, series, dest, watch, parallel } = require('gulp')
const sass = require('gulp-sass');
const concat = require('gulp-concat');
const gulpServer = require('gulp-webserver')
const webpackStream = require('webpack-stream');
const proxy = require('http-proxy-middleware');
const path = require('path');


function copyHtml() {
  return src('./src/views/**/*.html')
    .pipe(dest('./dev/'))
  // todo...
}

function compileCSS() {
  return src('./src/style/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('all.css'))
    .pipe(dest('./dev/'))
}


function compilejs() {
  // return src('./src/js/**/*.js')
  //   .pipe(dest('./dev/'))
  return src('./src/js/app.js')
    .pipe(webpackStream({
      // 指定编译的模式，development 开发模式，production :生产模式，压缩，优化
      mode: 'development',
      devtool: "inline-source-map",
      //打包的入口文件
      entry: {
        main: './src/js/app.js',
        detail: './src/js/Detail.js'
      },
      output: {
        //完整的输出目录
        path: path.resolve(__dirname, './dev/'),
        filename: '[name]-all.js'
      },
      module: {
        rules: [
          {
            //正则匹配
            test: /\.js$/,
            //排除的文件夹
            exclude: /node_modules/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],//预设
                plugins: ['@babel/plugin-transform-runtime']
              }
            }
          }, {
            test: /\.html$/,
            loader: 'string-loader'
          }
        ]
      }

    }))
    .pipe(dest('./dev/'))
}

function startServer() {
  return src('./dev/')
    .pipe(gulpServer({
      port: 8008,
      host: '192.168.43.107',
      //是否支持热更新
      livereload: true,
      //打开浏览器
      open: true,
      //目录
      directoryListing: false,
      middleware: [
        proxy('/api', {
          //代理的目标地址
          target: "http://127.0.0.1:3003/",
          // target: "https://m.lagou.com/",
          //是否支持跨域
          changeOrigin: true,
          pathRewrite: {
            '^/api': ''
          }
        })
      ]

    }));
}

function copyLibs() {
  return src('./src/libs/**/*.*')
    .pipe(dest('./dev/libs/'))
}

function copyImages() {
  return src('./src/images/**/*.*')
    .pipe(dest('./dev/images/'))
}

function watchFile() {
  watch('./src/style/**/*.scss', (cb) => {
    compileCSS();
    cb();
  })

  watch('./src/js/**/*.js', (cb) => {
    compilejs();
    cb();
  })

  watch('./src/views/**/*.html', (cb) => {
    copyHtml();
    compilejs();
    cb();
  })
}

exports.default = series(parallel(copyHtml, copyImages, copyLibs), compilejs, compileCSS, startServer, watchFile);